﻿using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using log4net;

namespace AlanAamy.Net.TemperatureConverter.Infrastructure.Frameworks.RX
{
    public class ObservableSequence<T,U> : IObservable<T>
    {
        private readonly Subject<T> _innerObservable = new Subject<T>();
        public event EventHandler ValueChanged = delegate { };
        public event EventHandler UnitChanged = delegate { };
        private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private T _value;
        private U _unit;
        public T Value
        {
            get { return _value; }
            set
            {
                _value = value;
                _innerObservable.OnNext(value);
                var localValueChanged = ValueChanged;
                localValueChanged(this, new EventArgs());
            }
        }

        public U Unit
        {
            get { return _unit; }
            set { 
                _unit = value;
                var localUnitChanged = UnitChanged;
                localUnitChanged(this,new EventArgs()); 
            }
        }

        public IDisposable Subscribe(IObserver<T> observer)
        {
            return _innerObservable
                .DistinctUntilChanged()
                .AsObservable()
                .Do(o => {Log.Debug(string.Format("OnNext {0}",o));})
                .Subscribe(observer);
        }

        public IObservable<T> GetObservable()
        {
            return this;
        }
    }
}
